package cn.com.lms.business.livecourse.service;

import cn.com.lms.business.core.util.CurrentUserInstance;
import cn.com.lms.business.livecourse.constant.TencentImConstants;
import cn.com.lms.business.livecourse.persistence.entity.TencentImAuth;
import cn.com.lms.business.livecourse.util.HttpClientUtil;
import cn.com.lms.business.livecourse.util.TencentImUtil;
import cn.com.lms.business.user.persistence.entity.SysUserVo;
import cn.com.lms.business.user.service.SysUserVoService;
import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Random;
// 使用旧版本 base64 编解码实现增强兼容性


/**
 * 腾讯即时通信服务
 *
 * @author barry
 * @date 2020/3/19
 **/
@Service
public class TencentImService {

    /**
     * 生成用户签名串（sdk登录使用）
     * @return
     */
    public TencentImAuth genUserSign (String imUserId) {
        TencentImAuth tia = new TencentImAuth();
        tia.setAppId(TencentImConstants.SDK_APP_ID);
        tia.setAppUserId(imUserId);
        tia.setAppUserSign(TencentImUtil.genSig(imUserId, 2 * 86400)); // 默认两天有效期
        return tia;
    }

    /**
     * 创建群组（音视频聊天室）
     * @param groupName 指定的群名称
     * @param groupId  指定的groupId
     */
    public boolean createLiveCourseGroup(String groupName, String groupId) {
        String admin = TencentImConstants.ADMIN_ACCOUNT;
        TencentImAuth tia = this.genUserSign(admin);
        String userSig = tia.getAppUserSign();
        Random random = new Random();
        int randomNUm1 = random.nextInt(Integer.MAX_VALUE);
        int randomNUm2 = random.nextInt(Integer.MAX_VALUE);
        long randomNum = (long)randomNUm1 + (long)randomNUm2;
        String url = "https://console.tim.qq.com/v4/group_open_http_svc/create_group?sdkappid=" + TencentImConstants.SDK_APP_ID + "&identifier=" + admin + "&usersig=" + userSig + "&random=" + randomNum + "&contenttype=json";
        // TencentImUtil.getImUserId("李宁宁", "17043")  \"Owner_Account\": \"" + admin + "\", // 群主的 UserId（选填）
        String body = "{ " +
                "\"Type\": \"AVChatRoom\", " +  // 群组类型：Private/Public/ChatRoom/AVChatRoom/BChatRoom（必填）
                "\"Name\": \"" + groupName + "\", " + // 群名称（必填）
                "\"GroupId\": \"" + groupId + "\"" + // 指定群id
                "}";
        System.out.println("body = " + body);
        String response = "";
        try {
            response = HttpClientUtil.post(url, body);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        System.out.println("response = " + response);
        JsonParser parser = new JsonParser();
        JsonObject jsonObject  = parser.parse(response).getAsJsonObject();
        String actionStatus = jsonObject.get("ActionStatus").getAsString();
        int errorCode = jsonObject.get("ErrorCode").getAsInt();
        if ("OK".equals(actionStatus) && 0 == errorCode) {
            return  true;
        }
        return false;
    }


    /**
     * 解散群组（音视频聊天室）
     * @param groupId  指定的groupId
     */
    public boolean destroyLiveCourseGroup(String groupId) {
        String admin = TencentImConstants.ADMIN_ACCOUNT;
        TencentImAuth tia = this.genUserSign(admin);
        String userSig = tia.getAppUserSign();
        Random random = new Random();
        int randomNUm1 = random.nextInt(Integer.MAX_VALUE);
        int randomNUm2 = random.nextInt(Integer.MAX_VALUE);
        long randomNum = (long)randomNUm1 + (long)randomNUm2;
        String url = "https://console.tim.qq.com/v4/group_open_http_svc/destroy_group?sdkappid=" + TencentImConstants.SDK_APP_ID + "&identifier=" + admin + "&usersig=" + userSig + "&random=" + randomNum + "&contenttype=json";
        // TencentImUtil.getImUserId("李宁宁", "17043")  \"Owner_Account\": \"" + admin + "\", // 群主的 UserId（选填）
        String body = "{\"GroupId\": \"" + groupId + "\"}";  // 指定群id
        System.out.println("body = " + body);
        String response = "";
        try {
            response = HttpClientUtil.post(url, body);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        System.out.println("response = " + response);
        JsonParser parser = new JsonParser();
        JsonObject jsonObject  = parser.parse(response).getAsJsonObject();
        String actionStatus = jsonObject.get("ActionStatus").getAsString();
        int errorCode = jsonObject.get("ErrorCode").getAsInt();
        if ("OK".equals(actionStatus) && 0 == errorCode) {
            return  true;
        }
        return false;
    }


    /**
     * 发送群消息（普通）
     * @param groupId
     * @param message
     */
    public boolean sendGroupMessage(String groupId, String message) {
        String admin = TencentImConstants.ADMIN_ACCOUNT;
        TencentImAuth tia = this.genUserSign(admin);
        String userSig = tia.getAppUserSign();
        Random random = new Random();
        int randomNUm1 = random.nextInt(Integer.MAX_VALUE);
        int randomNUm2 = random.nextInt(Integer.MAX_VALUE);
        long randomNum = (long)randomNUm1 + (long)randomNUm2;
        String url = "https://console.tim.qq.com/v4/group_open_http_svc/send_group_msg?sdkappid=" + TencentImConstants.SDK_APP_ID + "&identifier=" + admin + "&usersig=" + userSig + "&random=" + randomNum + "&contenttype=json";
        System.out.println("url = " + url);

        String body =  "{\n" +
            "  \"GroupId\": \"" + groupId + "\",\n" +
            "  \"Random\": " + randomNUm1 + ", \n" +   // 随机数字，五分钟数字相同认为是重复消息
            "  \"MsgPriority\": \"High\", \n" +   // 消息优先级
            "  \"ForbidCallbackControl\":[\n" +
            "          \"ForbidBeforeSendMsgCallback\",\n" +
            "          \"ForbidAfterSendMsgCallback\"], \n" +   // 禁止回调控制选项
            "  \"MsgBody\": [ \n" + // 消息体，由一个element数组组成，详见字段说明
            "      {\n" +
            "          \"MsgType\": \"TIMTextElem\",\n" +    // 文本
            "          \"MsgContent\": {\n" +
            "              \"Text\": \"" + message + "\"\n" +
            "          }\n" +
            "      }\n" +
            "  ]\n" +
        "}";

        System.out.println("body = " + body);
        String response = "";
        try {
            response = HttpClientUtil.post(url, body);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        System.out.println("response = " + response);
        JsonParser parser = new JsonParser();
        JsonObject jsonObject  = parser.parse(response).getAsJsonObject();
        String actionStatus = jsonObject.get("ActionStatus").getAsString();
        int errorCode = jsonObject.get("ErrorCode").getAsInt();
        if ("OK".equals(actionStatus) && 0 == errorCode) {
            return  true;
        }
        return false;
    }
}
